#usr/bin/env python
#conding:utf-8
# 吕康宁，2020.7.1
import re,os,sys
import time,datetime
import base64
import binascii
import numpy as np
import pandas as pd
# import ffmpy3

# 数据分两部分，一是需要更新的数据，二是需要独立存储的数据，存储的数据需要符合表格的字段，也就是mesg_to_db_field。2020.08.31吕康宁
mesg_to_db_field={'lbs': '0', 'mileage': '0', 'speed': '0', 'othermesg':{}, 'wifi': '0', 
		  'oil_use': '0', 'dirct': '0', 'scanner': '0', 'rssi': '0', 'efence_alarm': '0', 
		  'status': '0', 'remark': '0', 'heart_rate': '0', 'speed_alarm': '0', 'battery': '0', 
		  'blood_pres': '0', 'stop_time': '0','sos_alarm': '0', 'step_count': '0', 
		  'heart_alarm': '0', 'device_id':'0', 'dev_upload': '0', 'obd': '0', 'blood_alarm': '0', 
		  'lng': '0', 'serv_receive': '0', 'track_type': '0', 'location': '0', 'lat': '0', 'hard_verson': '0'}


def get_track_type(raw_data):
	this_track_type='0'
	if raw_data.get('lng')!=None and raw_data.get('lng')!='0':
		this_track_type='satelite'
	elif raw_data.get('wifi')!=None and raw_data.get('wifi')!='0':
		this_track_type='wifi'
	elif raw_data.get('lbs')!=None and raw_data.get('lbs')!='0':
		this_track_type='lbs'

	return this_track_type

jiai_command_result_dict={'IWAP33': 'work_model', 'IWAP86': 'health_rate', 'IWAP12': 'sos', 'IWAP21': 'step_cunt_btn',
						  'IWAP85': 'time_remind', 'IWAP16': 'call_now', 'IWAP17': 'factory_set', 'IWAP18': 'dev_reset', 
						  'IWAP31': 'turn_off_dev', 'IWAPXL': 'heart_rate_detect', 'IWAPXY': 'health_detect'}

# 把音频，图片等存储在本地的函数
def save_to_file(device_id,send_name,content):
	# 转换成时间数组
	now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	timeArray = time.strptime(now, "%Y-%m-%d %H:%M:%S")
	# 转换成时间戳
	timestamp = time.mktime(timeArray)
	# if x == 'tk_mesg':
	# 	send_name = 'amr'
	# elif x == 'img_data':
	# 	send_name = 'jpeg'
	# 获取当前设备号,获取现在的时间年月日,获取现在时间的时间戳时间,然后存入文件中
	pk_name = "{}.{}".format(int(timestamp), send_name)
	plat_form=sys.platform[0:3]
	save_path=''
	if plat_form=='win':
		save_path="E:\\tracker\\tracker_app\\static\\multi_data\\{0}\\{1}\\".format(device_id, datetime.datetime.now().strftime('%Y-%m-%d'))
	else:
		save_path="/root/tracker/tracker_app/static/multi_data/{0}/{1}/".format(device_id, datetime.datetime.now().strftime('%Y-%m-%d'))
	
	if not os.path.exists(save_path):  # 判断当前路径是否存在，没有则创建new文件夹/root/device
		os.makedirs(save_path)

	file_path=save_path + pk_name

	if send_name=='amr':
		pk_name1 = "{}.{}".format(int(timestamp), 'mp3')
		if not os.path.exists(file_path):
			with open(file_path, "wb") as f:
				f.write(content)
			
			file_path1=save_path + pk_name1
			# 判断是否存在音频文件
			if os.path.exists(file_path):
				cmd='ffmpeg -i '+file_path+' -acodec libmp3lame '+file_path1
				os.popen(cmd)
				# 会堵塞，os的popen是异步的
				# ffmpy3.FFmpeg(inputs={file_path: None}, outputs={file_path1: ['-ac','1','-ar','8000']}).run()
		pk_name=pk_name1
	else:
		with open(file_path, "wb") as f:
			f.write(content)

	src_path='/static/multi_data/{0}/{1}/{2}'.format(device_id, datetime.datetime.now().strftime('%Y-%m-%d'),pk_name)
	return src_path

def handle_wifi(wifi):
	all_wifi=[]
	try:
		wifi=wifi.decode()
		wifi=wifi.split('&')
		for x in wifi:	
			x=x.split('|')
			if len(x)==3:
				wifi_signal=150-int(x[2])
				wifi_dict={'ssid':x[0],'mac':x[1].replace('-',':'),'rssi':wifi_signal}
				all_wifi.append(wifi_dict)
		wifi_signal_max=pd.DataFrame(all_wifi)
		wifi_signal_max.sort_values(by=['rssi'],ascending=True,inplace=True)
	except:
		wifi=wifi.split(b'&')
		for x in wifi:	
			x=x.split(b'|')
			if len(x)==3:
				wifi_signal=150-int(x[2].decode())
				wifi_ssid=x[0]
				try:
					wifi_ssid=wifi_ssid.decode()
				except:
					wifi_ssid=binascii.hexlify(wifi_ssid).decode()
				wifi_dict={'ssid':wifi_ssid,'mac':x[1].decode().replace('-',':'),'rssi':str(wifi_signal)}
				all_wifi.append(wifi_dict)
		wifi_signal_max=pd.DataFrame(all_wifi)
		wifi_signal_max.sort_values(by=['rssi'],ascending=True,inplace=True)

	return all_wifi



def jiai_analysis(data,rece_time,port,mesg_redis='0',device_id='0'):
	# 数据分两部分，一是需要更新的数据，二是需要独立存储的数据，存储的数据需要符合表格的字段，也就是mesg_to_db_field。2020.08.31吕康宁
	add_to_db={'lbs': '0', 'mileage': '0', 'speed': '0', 'othermesg':{}, 'wifi': '0', 
			  'oil_use': '0', 'dirct': '0', 'scanner': '0', 'rssi': '0', 'efence_alarm': '0', 
			  'status': '0', 'remark': '0', 'heart_rate': '0', 'speed_alarm': '0', 'battery': '0', 
			  'blood_pres': '0', 'stop_time': '0','sos_alarm': '0', 'step_count': '0', 
			  'heart_alarm': '0', 'device_id':'0', 'dev_upload': '0', 'obd': '0', 'blood_alarm': '0', 
			  'lng': '0', 'serv_receive': '0', 'track_type': '0', 'location': '0', 'lat': '0', 'hard_verson': '0'}
	all_data={}
	response=b'0'
	d_head=data[0:6].decode()
	data_kind=d_head[2:]

	add_to_db['save_kind']='yes'
	# 用status字段存储在线离线信息，并存储到历史数据中，方便计算在线离线率2020.9.03吕康宁,有时间再梳理。
	all_data['on_off_line']='online'
	all_data['device_id']=device_id
	all_data['receive_port']=[port,'jiai']
	all_data['serv_receive']=rece_time

	d_body=data[6:-1]

	if data_kind=='AP00':
		
		device_id=d_body.decode()
		all_data['device_id']=device_id
		response_time=datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
		response=b'IWBP00,'+response_time.encode()+b',8#'

	if data_kind in ['AP01','AP10']:

		# rule=rule+rb'(?P<date>\w{6})(?P<track_type>\w)(?P<lat>\d+\.\d+)N(?P<lng>\d+\.\d+)E(?P<speed>\d+|\d+\.\d)(?P<time>\w{6})(?P<dirct>\d+|\d+\.\d{2})(?P<gsm>\d{3})(?P<gps_num>\w{3})(?P<battery>\w{3})(?P<not_use>\d),(?P<tumble>\w{1,10})(?P<work_model>\w{2}),(?P<lbs>\S*)'
		rule=r'(?P<date>\w{6})(?P<track_type>\w)(?P<lat>\d+\.\d+)N(?P<lng>\d+\.\d+)E(?P<speed>\d+|\d+\.\d)(?P<time>\w{6})(?P<dirct>\d+|\d+\.\d{2})(?P<gsm>\d{3})(?P<gps_num>\w{3})(?P<battery>\w{3})(?P<not_use>\d)(?P<defence>\w{2})(?P<work_model>\w{2})'
		d_body=d_body.split(b',')
		
		if data_kind=='AP10':
			d_body=b','.join(d_body[0:8]).decode("utf8","ignore").split(',')+[d_body[8]]
		else:
			d_body=b','.join(d_body[0:5]).decode("utf8","ignore").split(',')+[d_body[5]]

		data0=re.search(rule,d_body[0]).groupdict()
		speed=data0['speed']
		dirct=data0['dirct']
		gps_num=str(int(data0['gps_num']))
		gsm=str(int(data0['gsm']))
		battery=str(int(data0['battery']))
		defence=str(int(data0['defence']))
		work_model=str(int(data0['work_model']))
		if speed=='000.1':
			speed='0'

		all_data.update(speed=speed,dirct=dirct,gps_num=gps_num,rssi=gsm,battery=battery,defence=defence,work_model=work_model)
		
		up_date=data0['date']
		up_time=data0['time']
		format_time = '20%s-%s-%s %s:%s:%s'%(up_date[0:2],up_date[2:4],up_date[4:6],up_time[0:2],up_time[2:4],up_time[4:6])
		# print(format_time)
		# bj_time=int(time.mktime(time.strptime(format_time.decode(), "%Y-%m-%d %H:%M:%S")))+8*3600
		# bj_time=datetime.datetime.fromtimestamp(bj_time).strftime("%Y-%m-%d %H:%M:%S")
		all_data['dev_upload']=format_time

		if data0['track_type']=='A':
			lng=float(int(data0['lng'][0:3])+float(data0['lng'][3:5])/60+float('0'+data0['lng'][5:])/60)
			lat=float(int(data0['lat'][0:2])+float(data0['lat'][2:4])/60+float('0'+data0['lat'][4:])/60)
			all_data['lng']=round(lng,5)
			all_data['lat']=round(lat,5)

		# sid=LAC,nid=CID
		lbs_dict={'MNC':d_body[2],'MCC':d_body[1],'sid':d_body[3],'nid':d_body[4],'rssi':'0'}
		all_data['lbs']=str([lbs_dict])

		wifi=d_body[5]

		if data_kind=='AP10':
			wifi=d_body[8]
			alarm_status=d_body[5]
			alarm_dict={'00':'0','01':'sos_alarm','02':'low_power','03':'dev_drop','04':'wear_remain','05':'fall_down','06':'fall_down','08':'heart_house'}
			# 用sos_alarm字段存储所有的设备主动报警信息。2020.9.01吕康宁
			all_data['sos_alarm']=str([alarm_dict[alarm_status]])
			country_title=d_body[6]
			attch_status=d_body[7]

		if wifi:
			wifi_data=handle_wifi(wifi)
			all_data['wifi']=str(wifi_data)

		response=b'IWBP'+data_kind[2:].encode()+b'#'

	elif data_kind=='AP02':
		d_body=d_body.split(b',')
		d_body=b','.join(d_body[1:-1]).decode("utf8","ignore").split(',')+[d_body[-1]]
		# print(d_body)
		lan_title=d_body[0]
		response_mark=d_body[1]
		lbs_num=d_body[2]
		MCC=d_body[3]
		MNC=d_body[4]
		lbs_list=[]
		for x in range(int(lbs_num)):
			lbs_data=d_body[4+x+1].split('|')
			lbs_dict={'MNC':MNC,'MCC':MCC,'sid':lbs_data[0],'nid':lbs_data[1],'rssi':lbs_data[2]}
			lbs_list.append(lbs_dict)

		all_data['lbs']=str(lbs_list)

		wifi=d_body[-1]

		if wifi:
			wifi_data=handle_wifi(wifi)
			all_data['wifi']=str(wifi_data)

		response=b'IWBP02#'

	elif data_kind=='AP03':
		d_body=d_body[1:].decode().split(',')
		rule=r'(?P<gsm>\d{3})(?P<gps_num>\w{3})(?P<battery>\w{3})(?P<not_use>\d)(?P<defence>\w{2})(?P<work_model>\w{2})'
		data0=re.search(rule,d_body[0]).groupdict()
		gps_num=str(int(data0['gps_num']))
		gsm=str(int(data0['gsm']))
		battery=str(int(data0['battery']))
		defence=str(int(data0['defence']))
		work_model=str(int(data0['work_model']))
		step_count=str(int(d_body[1]))
		tumble=str(int(d_body[2]))
		

		all_data.update(step_count=step_count,tumble=tumble,gps_num=gps_num,rssi=gsm,battery=battery,defence=defence,work_model=work_model)
		# print(all_data)
		response=b'IWBP03#'

	elif data_kind=='AP05':
		pass

	elif data_kind=='AP07':
		d_body=d_body[1:].split(b',')
		# print(d_body)

		time_data=d_body[0]
		mesg_count=d_body[1]
		mesg_num=d_body[2]
		package_len=d_body[3]
		voice_data=b','.join(d_body[4:])
		response=b'IWBP07,'+time_data+b','+mesg_count+b','+mesg_num+b',1#'

		# 从redis取出之前缓存的语音数据
		separate_package=mesg_redis.get(device_id+'_separate_package')
		if separate_package!=None:
			separate_package=eval(separate_package)
		else:
			separate_package={}

		separate_package_data={mesg_num:voice_data}
		separate_package.update(separate_package_data)

		if mesg_count==mesg_num:
			tk_data=b''
			for x in sorted(separate_package):
				tk_data+=separate_package[x]
			all_data['voice']=save_to_file(device_id,'amr',tk_data)
			all_data['sender']='device'
			separate_package={}
		else:
			add_to_db['save_kind']='no'
		
		# 更新redis上的数据
		mesg_redis.set(device_id+'_separate_package',str(separate_package))


	elif data_kind=='AP49':
		heart_rate=d_body[1:].split(b',')[0].decode()
		heart_rate=str(int(heart_rate))
		all_data['heart_rate']=heart_rate

	elif data_kind=='APHT':
		d_body=d_body[1:].decode().split(',')
		blood_pres={'h_pres':d_body[1],'l_pres':d_body[2]}
		all_data['heart_rate']=str(int(d_body[0]))
		all_data['blood_pres']=str(blood_pres)

	elif data_kind=='APHP':
		d_body=d_body[1:].decode().split(',')
		blood_pres={'h_pres':d_body[1],'l_pres':d_body[2]}
		all_data['heart_rate']=str(int(d_body[0]))
		all_data['blood_pres']=str(blood_pres)
		all_data['oxygen']=d_body[3]
		all_data['blood_glucose']=d_body[4]

	elif data_kind=='AP28':
		d_body=d_body[1:].split(b',')
		sender=d_body[0]
		attch_data=d_body[1]
		all_num=d_body[2]
		this_num=d_body[3]
		receive_result=d_body[4]
		
		voice_dict=mesg_redis.get(device_id+'voice_dict')

		if voice_dict!=None:
			voice_dict=eval(voice_dict)
			send_num=str(int(this_num.decode())+1).encode()
			send_data=''
			if receive_result==b'1':
				if all_num!=this_num:
					# print('voice_dict',voice_dict)
					send_data=voice_dict[int(send_num.decode())-1]
					send_data=bytes.fromhex(send_data)
					response=b'IWAP28,'+sender+b','+attch_data+b','+all_num+b','+send_num+b','+str(len(send_data)).encode()+b','+send_data+b'#'
				else:
					
					# tk_data=''
					# for x in sorted(voice_dict):
					# 	tk_data+=voice_dict[x]
					# tk_data=bytes.fromhex(tk_data)
					# all_data['tk_mesg']=save_to_file(device_id,'amr',tk_data)
					# all_data['sender']='request.user'
					# v_data=mesg_redis.get(device_id+'voice')
					# if v_data!=None:
					# 	v_data=v_data.split(',')[1]
					# 	v_data=base64.b64decode(v_data)
					# 	all_data['tk_mesg']=save_to_file(device_id,'amr',v_data)
					# 	all_data['sender']='request.user'
					# 	mesg_redis.delete(device_id+'voice')

					mesg_redis.delete(device_id+'voice_dict')
					print('del-bufferdata')
					all_data['command_name']='voice'
					all_data['command_result']='success'
			else:
				send_data=voice_dict[int(send_num.decode())-2]
				send_data=bytes.fromhex(send_data)
				response=b'IWAP28,'+sender+b','+attch_data+b','+all_num+b','+send_num+b','+str(len(send_data)).encode()+b','+send_data+b'#'

			# print('response-voice-------',response)

	elif data_kind==b'APTM':
		pass

	elif 'IW'+data_kind in jiai_command_result_dict:
		all_data['command_name']=jiai_command_result_dict['IW'+data_kind]
		command_result=''
		print('command_result====>',d_body)
		if command_result=='1' or command_result=='':
			command_result='success'
		elif command_result=='0':
			command_result='failed'

		all_data['command_result']=command_result


	all_data['track_type']=get_track_type(all_data)
	
	# handle_data=all_data.copy()
	# for x in handle_data:
	# 	if handle_data[x]=='0':
	# 		all_data.pop(x)


	# 下行数据处理，从redis取出服务器下发设备的数据，记录设备接收结果的反馈，多媒体数据进行本地存储，记录多媒体文件路劲，推给store模块存储和更新
	if all_data.get('command_result')!=None and all_data.get('command_name')!=None:
		comd_detail=mesg_redis.get(device_id+all_data['command_name'])
		print('comd_detail=========>',comd_detail)
		if comd_detail!=None:
			comd_detail=eval(comd_detail)
			comd_detail['command_result']=all_data['command_result']
			command_name=all_data['command_name']

			if command_name in ['voice','picture']:
				file_type={'voice':'amr','picture':'jpeg'}
				v_data=comd_detail['command_value']
				v_data=v_data.split(',')[1]
				v_data=base64.b64decode(v_data)
				file_path=save_to_file(device_id,file_type[command_name],v_data)
				all_data[command_name]=file_path
				comd_detail['command_value']=file_path
			else: 
				all_data[command_name]=comd_detail['command_value']

			# 存入redis，在store模块打包处理
			mesg_redis.delete(device_id+command_name)
			# 命令执行状态清理
			mesg_redis.delete(device_id+'command_excuting')
			mesg_redis.lpush(device_id+'command_log',str(comd_detail))

	add_to_db.update(all_data)
	othermesg={}
	for x in all_data:
		if x not in mesg_to_db_field:
			othermesg[x]=add_to_db.pop(x)

	add_to_db['othermesg']=str(othermesg)
	
	add_to_db['response']=response


	return add_to_db


def jiai_first_handle(datas):
	data_handled=[]
	if datas.startswith(b'IW') and datas.endswith(b'#'):
		datas=datas.split(b'IWAP')[1:]

		for data in datas:
			data=b'IWAP'+data
			data_handled.append(data)
		return {'normal_data':data_handled}
	else:
		return 'buffer_data'

# ttdd=b'IWAP07,20190824124117,4,2,1024,\xd2Ct\xec\x0cp#'
# print(jiai_first_handle(ttdd))


# data=b'IWAP07,20190824125139,2,2,1024,\x0c\n<?\x96\xd9\x83g\xe9F\x8e\xa2E2\x0c\n<?\x96\xd9\x83g\xe9F\x8e\xa2E2\x0c\n<?\x96\xd9\x83g\xe9F\x8e\xa2E2\x0c\xaax7\xdf~~\xb5\xc3\x99\\aB\xd4\x0c\xecW\xfe\xff\xfd\xe1_\xae\x8f/\xff\'t\x0c\xf3\xc2\xd5\xff\xfeX\xe1\xdd3W\xe4\xa3\xda\x0c\xcc\x18\x1a\xdf\xde\xd6\x0f\xdb\x9c\x1c:o\x9a\x0cl$\xee\xff\xff\xca\'e\xbdK\x9b\xf1\x18\x0c\x00\x8a-\xbe\xffMuj\x93\\\x8ej|\x0c4\x81\x0f\xff\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b73vXp\xb5c\xf8\x08\xbc\x0c\xa4\xd2\x97\x96\xdf\x88\x17I\x10e\x0b\xa3\xfa\x0cB\xd2\x93wi\xebE!\xaa\x0bB\x96\x86\x0cZ\x90\x95\x92\xdf\xb2?J\x15R\x1dA\xa2\x0cZ,\x97\xb2\xcd\x83^\xa6\x9b\x0eR.\x98\x0cZ,\x95\xb6\xdd\xa1^M\x94\xd2q\xce\xec\x0c\xa4\xdf\x97\xb5\xdf\x8a\xc4\r\x94\xaa3lB\x0c\xa4T\x95\xb1\xdf\xb1~\xa64\x0f\xe6\xe1v\x0c\xe2\xec\x93\xba\xcb\xf5\xce\xa8\xba\xcf@\xb5^\x0cu\xf0\x9f\x92\xfeI\x85\x83\x8c/g\xec\x80\x0c\xa4\x7f\x9e\xd7S\xa4\xae\xe2\xb59fR\xf0\x0cIR\x9b\xff\xe7\xf9V\xa9\xabL\xf1\x9dh\x0c\x85q\x9f\xbf\xde\xff\xb0\xd9\x0b\x1fcN\\\x0c\xec\x18\xd2\xb7\xf4\xab\x1at"#'
# data1=b'IWAP01080524A2232.9806N11404.9355E000.1061830323.8706000908000502,460,0,9520,3671,HOME|74-DE-2B-44-88-8C|97&HOME1|74-DE-2B-44-88-8C|97&HOME2|74-DE-2B-44-88-8C|97&HOME3|74-DE-2B-44-88-8C|97#'
# data2=b'IWAPHT,60,130,85#'
# data3=b'IWAP01190824V0000.0000N00000.0000E000.1163213323.8710000006900000,460,0,9380,4502,\x08\x10y\xa09\x14a|dc-fe-18-e6-0e-77|62&a|24-69-68-86-dc-de|80&a|a0-91-c8-3e-2c-80|84#'
# data4=b'IWAP02,zh_cn,0,6,460,0,9380|4502|-7,9345|4083|-4,9380|4501|-1,9345|4082|1,9380|4432|4,9380|3802|5,3,a|8c-c7-d0-0c-ab-c0|65&a|8c-c7-d0-0c-ab-c0|65&a|30-a1-fa-67-dd-25|83#'
# data5=b'IWAPHP,75,134,78,96,0.0#'
# data6=b'IWAP10080524A2232.9806N11404.9355E000.1061830323.8706000908000502,460,0,9520,3671,00,zh-cn,00,HOME|74-DE-2B-44-88-8C|97&HOME1|74-DE-2B-44-88-8C|97&HOME2|74-DE-2B-44-88-8C|97&HOME3|74-DE-2B-44-88-8C|97#'
# data7=b'IWAP03,06000908000102,5555,30#'
# data8=b'IWAP49,68#'
# data9=b'IWAP07,20200702114542,3,1,1024,#!AMR\n\x0c\n<?\x96\xd9\x83g\xe9F\x8e\xa2E2\x0c\n<?\x96\xd9\x83g\xe9F\x8e\xa2E2\x0c\n<?\x96\xd9\x83g\xe9F\x8e\xa2E2\x0c\xff\x81\xc3\xff\xff\x8e\xe7B\x99g\x82\x10\xb4\x0c,x\xeb\xdf\xff\xb6\x7fo\xa2KS\'t\x0cJ\xb9u\xfe\xde\xcd\xbb\xb5\x11\xbfMTp\x0c)L\x1f\xf7\xff\xebQV?\xfa\xb5\xd8.\x0c\x0b\x7f\x0f\xdf\xfb\xd2\x7fm\x92;\xea0\xd0\x0c,\x00/\xf7o\x8aAp.\x1a\xe2~p\x0c\xb9W;\xfb\xfd9]\xbdjP\xb3\xed\xb4\x0c\x98(5\xf7s\xd4na\xaf\xcf\xfep\xc4\x0c\x98\x18\x9a\xf7S\xae\xba\xb3;C\xb1Q\x04\x0c\x00\xc29\xf7\xef\xd2I||\xcf\x8b\x17z\x0cjx5\xfew\xcdQ\xf0;\x1b6\x134\x0c\xcc\x8a:\xff\xeb\x84\x9ek\xabE\xd0\xb3\xd6\x0c,\x98\xfe\xff\xdd\x86\xcdAV\x1f\xa8\xec\xe8\x0c\xccW\xe1\xffsR\x9a\xe5\x0f\x1f\xa4]\xb0\x0c\x00\x00\x00\xc0\x0c\x96[\x08Ic\xcb\x9f\x8c\x0c\xc4\x00\x1f\xdf\xff\x7f\xf1\xeag\x1c\xc0\xf8*\x0c1n?\xdb\xce4\r\xd9\xa4Nm\xfc,\x0c\x8a\x9cR\x1f\xf7\x03\x9a\x87\xb5\x94p|\x08\x0c8\xe4\x1a\xf3\xfe\xe0\x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8710000009300000,460,0,30752,28263,01,zh-cn,00,a|78-f5-57-0a-ef-44|89&a|78-f5-57-0a-ef-44|89&a|78-58-60-99-ac-6c|93#'

# data10=b'IWAPHT,60,130,85#IWAPHT,60,130,85#'
# data11=b'IWAP02,zh_cn,0,6,460,0,9345|3883|-6,9345|3693|-7,9345|3811|-4,9345|3691|0,9345|3692|0,9345|3882|0,3,\xdc\xc6K,_la|40-f4-20-d7-61-62|30&a|10-e9-53-cb-ab-61|72&a|dc-fe-18-b1-2d-a6|75#'
# print(jiai_first_handle(data10))
# print(jiai_analysis(data11,'race_time','port'))